const omit = require('lodash/omit')
const { db } = require('../config')
const { command } = require('../config')
const _ = command
const { obd_collection } = require('../config')
exports.main = async (event, context) => {
    const data = event.data;
    const userInfo = event.userInfo;
    const condition = data.condition || {};
    const pageSize = data.pageSize || 50;
    const page = data.page || 0;

    const grid = condition.grid;
    const staff = condition.staff;
    const assign = condition.assign;

    const region = condition.region || userInfo.region;
    const userGrid = userInfo.grid;
    const otherCondition = omit(condition, ['assign', 'grid', 'region', 'isNewAdd'])
    let _condi = { region, grid }
    if (assign) {
        _condi['staff'] = assign === '1' ? _.neq('') : _.eq('')
        _condi.grid = assign === '2' ? _.in([grid, '']) : grid
    }

    Object.keys(otherCondition).forEach(key => {
      otherCondition[key] && (_condi[key] = new RegExp(otherCondition[key], 'i'))
    })

    if (condition.hasOwnProperty('isNewAdd')) {
        if (condition.isNewAdd == "是") {
            _condi.isNewAdd = condition.isNewAdd;
        } else {
            _condi.isNewAdd = _.neq("是");
        }
    }

    console.log('查询条件', _condi)
    // const collection = '1order_list2';
    const countRs = await db.collection(obd_collection).where(_condi).count();
    const lists = await db.collection(obd_collection)
        .where(_condi)
        .skip(page * pageSize)
        .limit(pageSize)
        .get();

    return { total: countRs.total, data: lists.data, page, pageSize };
}